/**
 * 初始化演示数据
 * 为数据库添加一些示例的医院、科室和设备数据
 */

import { hospitalDB, HospitalData, DepartmentData, MedicalEquipmentData } from './indexedDB'

// 示例医院数据
const sampleHospitals: Omit<HospitalData, 'id' | 'createdAt' | 'updatedAt'>[] = [
  {
    name: '中心医院',
    address: '北京市朝阳区建国路88号',
    center: [116.4074, 39.9042],
    bounds: {
      north: 39.9052,
      south: 39.9032,
      east: 116.4084,
      west: 116.4064
    },
    floors: ['floor_1', 'floor_2', 'floor_3'],
    metadata: {
      type: '综合医院',
      level: '三级甲等',
      beds: 800,
      established: 1985
    }
  },
  {
    name: '儿童医院',
    address: '北京市西城区复兴门内大街156号',
    center: [116.3663, 39.9050],
    bounds: {
      north: 39.9060,
      south: 39.9040,
      east: 116.3673,
      west: 116.3653
    },
    floors: ['floor_1', 'floor_2'],
    metadata: {
      type: '专科医院',
      level: '三级甲等',
      beds: 400,
      established: 1978
    }
  }
]

// 示例科室数据
const sampleDepartments: Omit<DepartmentData, 'id' | 'createdAt' | 'updatedAt'>[] = [
  {
    hospitalId: 'hospital_1',
    name: '急诊科',
    type: 'emergency',
    description: '24小时急诊服务',
    capacity: 50,
    currentLoad: 32,
    status: 'active',
    buildingId: 'building_1',
    floorId: 'floor_1',
    position: [116.4074, 39.9042],
    contact: {
      phone: '010-12345678',
      email: 'emergency@hospital.com'
    },
    operatingHours: {
      start: '00:00',
      end: '23:59'
    },
    metadata: {
      director: '张主任',
      nurses: 12,
      doctors: 8
    }
  },
  {
    hospitalId: 'hospital_1',
    name: '心内科',
    type: 'cardiology',
    description: '心脏内科专业诊疗',
    capacity: 30,
    currentLoad: 18,
    status: 'active',
    buildingId: 'building_1',
    floorId: 'floor_2',
    position: [116.4076, 39.9044],
    contact: {
      phone: '010-12345679',
      email: 'cardiology@hospital.com'
    },
    operatingHours: {
      start: '08:00',
      end: '18:00'
    },
    metadata: {
      director: '李主任',
      nurses: 10,
      doctors: 6
    }
  },
  {
    hospitalId: 'hospital_1',
    name: '外科',
    type: 'surgery',
    description: '外科手术和治疗',
    capacity: 40,
    currentLoad: 25,
    status: 'active',
    buildingId: 'building_1',
    floorId: 'floor_2',
    position: [116.4072, 39.9040],
    contact: {
      phone: '010-12345680',
      email: 'surgery@hospital.com'
    },
    operatingHours: {
      start: '08:00',
      end: '20:00'
    },
    metadata: {
      director: '王主任',
      nurses: 15,
      doctors: 10
    }
  },
  {
    hospitalId: 'hospital_2',
    name: '儿科门诊',
    type: 'pediatrics',
    description: '儿童疾病诊断和治疗',
    capacity: 25,
    currentLoad: 15,
    status: 'active',
    buildingId: 'building_2',
    floorId: 'floor_1',
    position: [116.3663, 39.9050],
    contact: {
      phone: '010-12345681',
      email: 'pediatrics@childhospital.com'
    },
    operatingHours: {
      start: '08:00',
      end: '17:00'
    },
    metadata: {
      director: '赵主任',
      nurses: 8,
      doctors: 5
    }
  }
]

// 示例医疗设备数据
const sampleEquipment: Omit<MedicalEquipmentData, 'id' | 'createdAt' | 'updatedAt'>[] = [
  {
    hospitalId: 'hospital_1',
    name: 'CT扫描仪',
    type: 'imaging',
    model: 'Siemens SOMATOM',
    serialNumber: 'CT001-2023',
    departmentId: 'dept_1',
    floorId: 'floor_1',
    position: [116.4075, 39.9043],
    status: 'active',
    purchaseDate: new Date('2022-01-15'),
    warrantyExpiry: new Date('2025-01-15'),
    lastMaintenance: new Date('2023-11-01'),
    nextMaintenance: new Date('2024-02-01'),
    manufacturer: '西门子',
    metadata: {
      operatingHours: 2400,
      scansPerformed: 15600,
      technician: '技师A'
    }
  },
  {
    hospitalId: 'hospital_1',
    name: 'MRI设备',
    type: 'imaging',
    model: 'GE Signa Pioneer',
    serialNumber: 'MRI001-2023',
    departmentId: 'dept_1',
    floorId: 'floor_1',
    position: [116.4077, 39.9041],
    status: 'maintenance',
    purchaseDate: new Date('2021-08-20'),
    warrantyExpiry: new Date('2024-08-20'),
    lastMaintenance: new Date('2023-12-01'),
    nextMaintenance: new Date('2024-01-15'),
    manufacturer: 'GE Healthcare',
    metadata: {
      operatingHours: 3200,
      scansPerformed: 8900,
      technician: '技师B'
    }
  },
  {
    hospitalId: 'hospital_1',
    name: '手术台',
    type: 'surgical',
    model: 'Trumpf TruSystem 7500',
    serialNumber: 'ST001-2023',
    departmentId: 'dept_3',
    floorId: 'floor_2',
    position: [116.4073, 39.9039],
    status: 'active',
    purchaseDate: new Date('2022-05-10'),
    warrantyExpiry: new Date('2025-05-10'),
    lastMaintenance: new Date('2023-10-15'),
    nextMaintenance: new Date('2024-01-15'),
    manufacturer: 'Trumpf Medical',
    metadata: {
      operatingHours: 1800,
      surgeries: 450,
      surgeon: '外科医生A'
    }
  },
  {
    hospitalId: 'hospital_2',
    name: '儿童监护仪',
    type: 'monitoring',
    model: 'Philips IntelliVue MX40',
    serialNumber: 'MON001-2023',
    departmentId: 'dept_4',
    floorId: 'floor_1',
    position: [116.3665, 39.9052],
    status: 'active',
    purchaseDate: new Date('2023-03-01'),
    warrantyExpiry: new Date('2026-03-01'),
    lastMaintenance: new Date('2023-11-20'),
    nextMaintenance: new Date('2024-02-20'),
    manufacturer: 'Philips Healthcare',
    metadata: {
      operatingHours: 720,
      patientsMonitored: 280,
      nurse: '护士A'
    }
  },
  {
    hospitalId: 'hospital_1',
    name: 'X光机',
    type: 'imaging',
    model: 'Canon CXDI-801C',
    serialNumber: 'XR001-2023',
    departmentId: 'dept_1',
    floorId: 'floor_1',
    position: [116.4071, 39.9045],
    status: 'active',
    purchaseDate: new Date('2022-09-12'),
    warrantyExpiry: new Date('2025-09-12'),
    lastMaintenance: new Date('2023-12-05'),
    nextMaintenance: new Date('2024-03-05'),
    manufacturer: 'Canon Medical',
    metadata: {
      operatingHours: 1500,
      xraysPerformed: 12000,
      technician: '技师C'
    }
  }
]

/**
 * 初始化演示数据
 */
export async function initializeDemoData(): Promise<void> {
  try {
    // 确保数据库已初始化
    await hospitalDB.initPromise
    
    console.log('开始初始化演示数据...')
    
    // 检查是否已有数据
    const existingHospitals = await hospitalDB.getAll('hospitals')
    if (existingHospitals.length > 0) {
      console.log('数据库中已有数据，跳过初始化')
      return
    }
    
    // 添加医院数据
    const hospitalIds: string[] = []
    for (let i = 0; i < sampleHospitals.length; i++) {
      const hospital = await hospitalDB.addHospital(sampleHospitals[i])
      hospitalIds.push(hospital.id)
      console.log(`添加医院: ${hospital.name}`)
    }
    
    // 更新科室数据的医院ID
    const departmentIds: string[] = []
    for (let i = 0; i < sampleDepartments.length; i++) {
      const dept = { ...sampleDepartments[i] }
      if (i < 3) {
        dept.hospitalId = hospitalIds[0] // 前3个科室属于第一个医院
      } else {
        dept.hospitalId = hospitalIds[1] // 其他科室属于第二个医院
      }
      
      const department = await hospitalDB.addDepartment(dept)
      departmentIds.push(department.id)
      console.log(`添加科室: ${department.name}`)
    }
    
    // 更新设备数据的医院ID和科室ID
    for (let i = 0; i < sampleEquipment.length; i++) {
      const equip = { ...sampleEquipment[i] }
      if (i < 3) {
        equip.hospitalId = hospitalIds[0] // 前3个设备属于第一个医院
        equip.departmentId = departmentIds[i] // 对应科室
      } else if (i === 3) {
        equip.hospitalId = hospitalIds[1] // 第4个设备属于第二个医院
        equip.departmentId = departmentIds[3] // 对应科室
      } else {
        equip.hospitalId = hospitalIds[0] // 其他设备属于第一个医院
        equip.departmentId = departmentIds[0] // 放在急诊科
      }
      
      const equipment = await hospitalDB.addMedicalEquipment(equip)
      console.log(`添加设备: ${equipment.name}`)
    }
    
    console.log('演示数据初始化完成！')
    console.log(`共添加了 ${hospitalIds.length} 个医院, ${departmentIds.length} 个科室, ${sampleEquipment.length} 个设备`)
    
  } catch (error) {
    console.error('初始化演示数据失败:', error)
    throw error
  }
}

/**
 * 清除所有数据（仅用于开发测试）
 */
export async function clearAllData(): Promise<void> {
  try {
    await hospitalDB.initPromise
    
    const hospitals = await hospitalDB.getAll('hospitals')
    const departments = await hospitalDB.getAll('departments')
    const equipment = await hospitalDB.getAll('medical_equipment')
    
    // 删除所有数据
    for (const hospital of hospitals) {
      await hospitalDB.deleteHospital(hospital.id)
    }
    
    for (const dept of departments) {
      await hospitalDB.deleteDepartment(dept.id)
    }
    
    for (const equip of equipment) {
      await hospitalDB.deleteMedicalEquipment(equip.id)
    }
    
    console.log('所有数据已清除')
  } catch (error) {
    console.error('清除数据失败:', error)
    throw error
  }
}